package net.jingkao.app.common;

import java.util.concurrent.Executors;

import android.os.Handler;
import android.os.Message;

/**
 * 
 * @author chao
 *
 */
public class ThreadUtils {
	
	static java.util.concurrent.ExecutorService threadPool = Executors.newSingleThreadExecutor();
	
	public static void sleep(long time){
		try {
			Thread.sleep(time);
		} catch (InterruptedException e1) {} 
	}
	
	public static void execute(Runnable task){
		threadPool.execute(task);
	}
	
	public static <T> void execute(final UITask<T> task){
		final Handler dataHandler = new DataHandler<T>(){

			@Override
			protected void handleData(T data) {
				task.handleData(data);
			}
			
		};
		
		ThreadUtils.execute(new Runnable(){

			@Override
			public void run() {
				Message msg = new Message();
				msg.obj = task.fetchData();
				dataHandler.sendMessage(msg);
			}
			
		});
	}
	
	
	public static abstract class UITask<T> {
		
		/**
		 * 获取数据
		 * 该方法将在线程池里面执行
		 * @return
		 */
		public abstract T fetchData();
		
		/**
		 * 处理数据
		 * 该方法将在UI现成中执行
		 * @param data
		 */
		public abstract void handleData(T data);
	}
}
